package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.DrawActivityRepository;
import cn.com.connext.scrm.repository.master.PrizeExtRepository;
import cn.com.connext.scrm.repository.master.PrizeRepository;
import cn.com.connext.scrm.repository.master.TmpMsgRecordRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.ProductService;
import cn.com.connext.scrm.service.mapper.TmpMsgRecordService;
import cn.com.connext.scrm.utils.DateUtils;
import cn.com.connext.scrm.utils.HttpUtils;
import cn.com.connext.scrm.utils.wechat.WxMessageSend;
import cn.com.connext.scrm.web.rest.ProductResource;
import cn.com.connext.scrm.web.rest.vm.TempSubScribeVm;
import cn.com.connext.scrm.web.rest.vm.Template;
import cn.com.connext.scrm.web.rest.vm.TemplateParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class TmpMsgRecordServiceImpl implements TmpMsgRecordService {
    @Autowired
    private TmpMsgRecordRepository tmpMsgRecordRepository;
    private final Logger log = LoggerFactory.getLogger(ProductResource.class);

    @Autowired
    private ProductService productService;
    @Autowired
    private PrizeGoodService prizeGoodService;
    @Autowired
    private TmpMsgRecordService tmpMsgRecordService;
    @Autowired
    private WxAPIService wxAPIService;

    @Autowired
    private WxMessageSend wxMessageSend;
    @Autowired
    private PrizeRepository prizeRepository;
    @Autowired
    private PrizeExtRepository prizeExtRepository;
    @Autowired
    private DrawActivityRepository drawActivityRepository;
    /**
     * 添加发送模板消息记录
     * @param entity
     */
    public void add(TmpMsgRecord entity) {
        tmpMsgRecordRepository.saveAndFlush(entity);
    }

    public List<TmpMsgRecord> findNoSendExpire() {
        List<TmpMsgRecord> list= tmpMsgRecordRepository.findNoSendExpire();
        return list;
    }

    @Override
    public void batchAdd(List<TmpMsgRecord> list) {
        tmpMsgRecordRepository.save(list);
    }

    @Override
    public JsonResult sendTemplateMsg(TempSubScribeVm vm) {
            JsonResult result = new JsonResult();
//            String Access_Token = wxAPIService.getThisAccessToken();
//            Template template=new Template();
//            template.setTemplate_id(Constants.GETPRIZETEMPLATEID);
//            template.setTouser(vm.getOpenId());
////        template.setPage("pages/home/index");
//            List<TemplateParam> paras=new ArrayList<TemplateParam>();
            PrizeGood prizeGood = prizeGoodService.findById(vm.getGoodId());
            DrawActivity one = drawActivityRepository.findOne(vm.getActivityId());
            if (null!= vm.getFlag() && 1== vm.getFlag()) {
                if (null !=one.getIsMessage() && 1!=one.getIsMessage()) {
                    log.info("未开启消息提醒，不发送微信订阅通知");
                    return result;
                }
                TmpMsgRecord record = new TmpMsgRecord();
                record.setPrizeId(vm.getPrizeId());
                record.setGood_type(prizeGood.getType());
                record.setCreateTime(new Date());
                record.setExpireTime(prizeGood.getExpireDate());
                record.setExpireCallDate(prizeGood.getExpireCallDate());
                record.setActivityId(vm.getActivityId());
                record.setGoodId(prizeGood.getId());
                record.setOpenId(vm.getOpenId());
                record.setGoodName(StringUtils.isNotBlank(one.getHelpActivityName())?one.getHelpActivityName():prizeGood.getGoodName());
                record.setHelpGoodRemark(one.getPrizeExpireMessageRemark());
                if (StringUtils.isNotBlank(one.getPrizeExpireMessage())) {
                    record.setExpireTemplateId(one.getPrizeExpireMessage());
                    record.setIsExpireMessage(1);
                }
                if (StringUtils.isNotBlank(one.getWinMessage())) {
                    record.setPrizeTemplateId(one.getWinMessage());
                }
                List<TemplateParam> templateParams = new ArrayList<>();

                //区分环境key
                String[] str ={};
//                if ("trial".equals(Constants.MINIPROGRAM_STATE)) {
//                    str = new String[]{"thing1","date6","thing3"};
//                } else {
                    str = new String[]{"thing1","date2","thing3"};
//                }
                templateParams.add(new TemplateParam(str[0],StringUtils.isNotBlank(one.getHelpActivityName())?one.getHelpActivityName():prizeGood.getGoodName()));
                templateParams.add(new TemplateParam(str[1], DateUtils.getStringToYYYYMMDD(new Date())));
                templateParams.add(new TemplateParam(str[2],StringUtils.isNotBlank(one.getWinMessageRemark())?one.getWinMessageRemark():"恭喜您获得以上奖品"));

                 result = wxMessageSend.sendMessageWx("page/reward/activityHistory/index", one.getWinMessage(), vm.getOpenId(), templateParams, record);
            } else {
                TmpMsgRecord record = new TmpMsgRecord();
                record.setCreateTime(new Date());
                record.setExpireTime(prizeGood.getExpireDate());
                record.setExpireCallDate(prizeGood.getExpireCallDate());
                record.setActivityId(vm.getActivityId());
                record.setGoodId(prizeGood.getId());
                record.setOpenId(vm.getOpenId());
                record.setGoodName(StringUtils.isNotBlank(one.getHelpActivityName())?one.getHelpActivityName():prizeGood.getGoodName());
                record.setHelpGoodRemark(one.getPrizeExpireMessageRemark());
//                    record.setPrizeTemplateId(Constants.GETPRIZETEMPLATEID);
                tmpMsgRecordService.add(record);
                log.info("订阅消息recordMsg保存 : ", record);
                result.setMessage("Send Success");
                result.setState(0);
            }

//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
//            String formatTime = sdf.format(new Date());
            //正式
//       paras.add(new TemplateParam("thing1","帝亚吉欧尊享卡券包"));
//        paras.add(new TemplateParam("date7",formatTime));
//       paras.add(new TemplateParam("thing4","点击此处查看详情"));
            //测试
//            paras.add(new TemplateParam("thing1",vm.getGoodName()));
//            paras.add(new TemplateParam("thing3","点击此处查看详情"));
//            paras.add(new TemplateParam("date6",formatTime));
//            template.setTemplateParamList(paras);
//            String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//            requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);
//            String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
//            JSONObject jsonResult = JSONObject.parseObject(resultString);
//            if(jsonResult!=null){
//                System.out.println(jsonResult);
//                int errorCode=jsonResult.getInteger("errcode");
//                String errorMessage=jsonResult.getString("errmsg");
//                if(errorCode==0){

//                }else{
//                    result.setMessage("订阅消息发送失败:"+errorCode+","+errorMessage);
//                    result.setState(1);
//                }
//            }else{
//                result.setMessage("订阅消息发送失败:jsonResult为空");
//                result.setState(1);
//            }
            return result;
        }

    @Override
    public JsonResult sendExpireTimeMsg() {
            List<TmpMsgRecord> list = tmpMsgRecordService.findNoSendExpire();
            JsonResult result = new JsonResult();
            if(list !=null && list.size() >0) {
                String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
                String Access_Token = wxAPIService.getThisAccessToken();
                Date d = new Date();
                List<TmpMsgRecord> tmList = new ArrayList<>();
                for (TmpMsgRecord record : list) {
//                    if (record.getExpireCallDate() != null) {
//                        if ((record.getExpireCallDate().getTime() < d.getTime() && d.getTime() <record.getExpireTime().getTime())) {
                            Template template = new Template();
                            template.setTemplate_id(Constants.EXPIRETEMPLATEID);
                            template.setTouser(record.getOpenId());
                            template.setPage("page/reward/enterPrize/index?activityId=ScanCodeCollectCoupons");
                            List<TemplateParam> paras = new ArrayList<TemplateParam>();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                            String formatTime = sdf.format(new Date());
                            String expireTime = sdf.format(record.getExpireTime());
                            //正式
                            //                    paras.add(new TemplateParam("thing1",record.getGoodName()));
                            //                    paras.add(new TemplateParam("date2",formatTime));
                            //                    paras.add(new TemplateParam("thing3","您有一份礼遇即将到期，点击可查看详情"));
                            //测试
                            paras.add(new TemplateParam("thing1", record.getGoodName()));
                            paras.add(new TemplateParam("time2", expireTime));
                            paras.add(new TemplateParam("thing3", "您有一份礼遇即将到期，点击可查看详情"));
                            template.setTemplateParamList(paras);
                            requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);
                            String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
                            JSONObject jsonResult = JSONObject.parseObject(resultString);
                            if (jsonResult != null) {
                                System.out.println(jsonResult);
                                int errorCode = jsonResult.getInteger("errcode");
                                String errorMessage = jsonResult.getString("errmsg");
                                if (errorCode == 0) {
                                    TmpMsgRecord tr = tmpMsgRecordService.findById(record.getId());
                                    tr.setExpireCreateTime(new Date());
                                    tr.setExpireTemplateId(Constants.EXPIRETEMPLATEID);
                                    tmList.add(tr);
                                    log.info("订阅消息recordMsg保存:{}", tmList);
                                    result.setMessage("Send Success");
                                    result.setState(0);
                                } else {
                                    result.setMessage("订阅消息发送失败:" + errorCode + "," + errorMessage);
                                    result.setState(1);
                                }
                            } else {
                                result.setMessage("订阅消息发送失败:jsonResult为空");
                                result.setState(1);
                            }
                        }
//                    }
//                }
                tmpMsgRecordService.batchAdd(tmList);
            }
            return result;
    }


    @Override
    public JsonResult sendCouponTemplateMsg(TempSubScribeVm vm) {
        JsonResult result = new JsonResult();
//        String Access_Token = wxAPIService.getThisAccessToken();
//        Template template=new Template();
//        template.setTemplate_id(Constants.GETPRIZETEMPLATEID);
//        template.setTouser(vm.getOpenId());
////        template.setPage("pages/home/index");
//        List<TemplateParam> paras=new ArrayList<TemplateParam>();
////        PrizeGood prizeGood = prizeGoodService.findById(vm.getGoodId());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
//        String formatTime = sdf.format(new Date());
//        //正式
////       paras.add(new TemplateParam("thing1","帝亚吉欧尊享卡券包"));
////        paras.add(new TemplateParam("date7",formatTime));
////       paras.add(new TemplateParam("thing4","点击此处查看详情"));
//        //测试
//        paras.add(new TemplateParam("thing1",vm.getGoodName()));
//        paras.add(new TemplateParam("thing3","点击此处查看详情"));
//        paras.add(new TemplateParam("date6",formatTime));
//        template.setTemplateParamList(paras);
//        String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//        requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);
//        String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
//        JSONObject jsonResult = JSONObject.parseObject(resultString);
//        if(jsonResult!=null){
//            System.out.println(jsonResult);
//            int errorCode=jsonResult.getInteger("errcode");
//            String errorMessage=jsonResult.getString("errmsg");
//            if(errorCode==0){
                List<PrizeGood> pgList = vm.getPgList();
                if(pgList !=null && pgList.size() >0){
                    TmpMsgRecord record=null;
                    List<TmpMsgRecord> list= new ArrayList<>();
                    for (PrizeGood pg:pgList ) {
                         record = new TmpMsgRecord();
                        record.setCreateTime(new Date());
                        record.setExpireTime(pg.getExpireDate());
                        record.setExpireCallDate(pg.getExpireCallDate());
                        record.setActivityId(vm.getActivityId());
                        record.setGoodId(pg.getId());
                        record.setOpenId(vm.getOpenId());
                        record.setGoodName(pg.getGoodName());
//                        record.setPrizeTemplateId(Constants.GETPRIZETEMPLATEID);
                        list.add(record);
                    }
                    tmpMsgRecordService.batchAdd(list);
                    log.info("订阅消息recordMsg保存:{}", list);
                }
//                result.setMessage("Send Success");
//                result.setState(0);
//            }else{
//                result.setMessage("订阅消息发送失败:"+errorCode+","+errorMessage);
//                result.setState(1);
//            }
//        }else{
//            result.setMessage("订阅消息发送失败:jsonResult为空");
//            result.setState(1);
//        }
        return result;
    }

    @Override
    public TmpMsgRecord findById(Integer id) {
        return tmpMsgRecordRepository.findById(id);
    }


    public JsonResult getScheme() {
        JsonResult result = new JsonResult();
        String requestUrl = "https://api.weixin.qq.com/wxa/generatescheme?access_token=ACCESS_TOKEN";
        String Access_Token = wxAPIService.getThisAccessToken();
        requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "{\r\n    \"jump_wxa\":\r\n    {\r\n        \"path\": \"page/drinkIq/home/index\",\r\n        \"query\": \"\"\r\n    },\r\n    \"is_expire\":false\r\n}");
        Request request = new Request.Builder()
            .url(requestUrl)
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build();
        try {
                Response response = client.newCall(request).execute();
                if (response != null) {
                    if (response.body() != null) {
                        String s = new String(response.body().bytes());
                        JSONObject jsonResult = JSON.parseObject(s);
                        if (jsonResult != null) {
                            System.out.println(jsonResult);
                            int errorCode = jsonResult.getInteger("errcode");
                            String errorMessage = jsonResult.getString("errmsg");
                            if (errorCode == 0) {
                                result.setData(jsonResult);
                                result.setMessage("Send Success");
                                result.setState(0);
                            } else {
                                result.setMessage("获取Scheme失败:" + errorCode + "," + errorMessage);
                                result.setState(1);
                            }
                        } else {
                            result.setMessage("获取Scheme失败:jsonResult为空");
                            result.setState(1);
                        }
                        return result;
                    }
                }
            }catch (Exception e){
                result.setMessage(e.getMessage());
                result.setState(1);
            }
        return result;
    }

    @Override
    public JsonResult sendNewExpireTimeMsg() {

        List<TmpMsgRecord> list= tmpMsgRecordRepository.findNewNoSendExpire();
        JsonResult result = new JsonResult();
        if(list !=null && list.size() >0) {
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
            String Access_Token = wxAPIService.getThisAccessToken();
            Date d = new Date();
            for (TmpMsgRecord record : list) {
                Template template = new Template();
                template.setTemplate_id(record.getExpireTemplateId());
                template.setTouser(record.getOpenId());
                template.setPage("page/reward/activityHistory/index");
                List<TemplateParam> paras = new ArrayList<TemplateParam>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");

                if (null == record.getExpireTime()) {
                    log.info("过期时间为空 跳出 record.id:{}",record.getId());
                    continue;
                }
                if (null!= record.getExpireCallDate() && DateUtils.timeToCompare(record.getExpireCallDate())==1) {
                    log.info("未到提醒时间 跳出 id:{} ",record.getId());
                    continue;
                }

                if (0 == record.getGood_type()) {
                    log.info("积分跳出");
                    continue;
                } else  if (1 == record.getGood_type()) {
                    //实物11
                    List<PrizeExt> byPrizeId = prizeExtRepository.findByPrizeId(record.getPrizeId());
                    if (byPrizeId.size()>0) {
                        log.info("存在地址信息维护 跳出");
                        continue;
                    }
                } else if (2 == record.getGood_type()) {
                    log.info("线下领取：待定；");
                } else if (3 == record.getGood_type()) {
                    Prize one = prizeRepository.findOne(record.getPrizeId());
                    //卡卷 微信已核销或者 核销卷已扫码
                    if (null == one || "1".equals(one.getVerifyStatus())||StringUtils.isNotBlank(one.getBeScanCode())) {
                        continue;
                    }
                    template.setPage("page/common/page/myCard/index");

                }
                paras.add(new TemplateParam("thing1", record.getGoodName()));
                paras.add(new TemplateParam("time2", sdf.format(record.getExpireTime())));
                paras.add(new TemplateParam("thing3", StringUtils.isNotBlank(record.getHelpGoodRemark())?record.getHelpGoodRemark():"您有一份礼遇即将到期，请点击查看"));
                template.setTemplateParamList(paras);
                requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);
                String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
                JSONObject jsonResult = JSONObject.parseObject(resultString);
                if (jsonResult != null) {
                    System.out.println(jsonResult);
                    int errorCode = jsonResult.getInteger("errcode");
                    String errorMessage = jsonResult.getString("errmsg");
                    if (errorCode == 0) {
                        TmpMsgRecord tr = tmpMsgRecordService.findById(record.getId());
                        tr.setExpireCreateTime(new Date());
                        tr.setIsExpireMessage(2);
//                        tmList.add(tr);
                        tmpMsgRecordService.add(tr);
                        log.info("订阅消息recordMsg保存:{}", JSON.toJSONString(tr));
                        result.setMessage("Send Success");
                        result.setState(0);
                    } else {
                        result.setMessage("订阅消息发送失败:" + errorCode + "," + errorMessage);
                        result.setState(1);
                    }
                } else {
                    result.setMessage("订阅消息发送失败:jsonResult为空");
                    result.setState(1);
                }
            }
        }
        return result;
    }

}

